package guild

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/os/gmlock"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/httpserver"
	"xr-game-server/dao/guilddao"
	"xr-game-server/dao/roledao"
	"xr-game-server/dto/guilddto"
	"xr-game-server/errercode"
)

// GetGuildApplications 获取公会申请列表
func GetGuildApplications(ctx context.Context, reqData *guilddto.GuildApplicationsReq) (*guilddto.GuildApplicationsRes, error) {
	roleId := httpserver.GetAuthId(ctx)

	roleData := roledao.GetRoleByRole(roleId)
	if roleData.GuildId == common.Zero {
		return nil, errercode.CreateCode(errercode.GuildNonExist)
	}
	if roleData.GuildId != reqData.GuildId {
		return nil, errercode.CreateCode(errercode.GuildNonExist)
	}
	lockKey := fmt.Sprintf(GuildLock, roleData.GuildId)
	defer gmlock.Unlock(lockKey)
	lockFlag := gmlock.TryLock(lockKey)
	if !lockFlag {
		return nil, errercode.CreateCode(errercode.SysBuyLimit)
	}
	members := guilddao.GetApply(roleData.GuildId)
	//
	res := guilddto.NewGuildApplicationsRes()
	for _, member := range members {
		memberRole := roledao.GetRoleByRole(member.RoleId)
		res.Applications = append(res.Applications, guilddto.NewGuildApplicationInfo(member, memberRole))
	}
	return res, nil
}

// GetGuildMemberInfo 获取公会成员信息
func GetGuildMemberInfo(ctx context.Context, req *guilddto.GuildMemberInfoReq) (*guilddto.GuildMemberInfoRes, error) {

	lockKey := fmt.Sprintf(GuildLock, req.GuildId)
	defer gmlock.Unlock(lockKey)
	lockFlag := gmlock.TryLock(lockKey)
	if !lockFlag {
		return nil, errercode.CreateCode(errercode.SysBuyLimit)
	}
	members := guilddao.GetGuildMembers(req.GuildId)
	//
	res := guilddto.NewGuildMemberInfoRes()
	for i, member := range members {
		memberRole := roledao.GetRoleByRole(member.RoleId)
		res.Members = append(res.Members, guilddto.NewGuildMemberInfo(members[i], memberRole))
	}
	return res, nil
}

// GetGuildInfo 获取公会信息
func GetGuildInfo(ctx context.Context, req *guilddto.GuildInfoReq) (*guilddto.GuildInfoRes, error) {

	lockKey := fmt.Sprintf(GuildLock, req.GuildId)
	defer gmlock.Unlock(lockKey)
	lockFlag := gmlock.TryLock(lockKey)
	if !lockFlag {
		return nil, errercode.CreateCode(errercode.SysBuyLimit)
	}
	member := guilddao.GetGuildMembers(req.GuildId)
	//
	return guilddto.NewGuildInfoRes(guilddao.GetGuild(req.GuildId), len(member)), nil
}
